import json

from PyQt5.QtWidgets import (
    QHBoxLayout,
    QVBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QWidget,
    QFileDialog,
    QComboBox,
    QMessageBox,
)
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from pydantic import BaseModel, Field, field_validator
from ..basic_grid_component import BasicGridComponent

# import gui.controls.envs as envs
from ..dlg_model_params import DlgModelParams
from ..utils import Utils
from ..util import util_key_map


# 定义 Pydantic 模型
class MeshPartitionData(BaseModel):
    globalSize: float = Field(
        description="全局网格尺寸",
        alias="globalSize",
        required=True,
    )


class MeshPartitionComponent(BasicGridComponent):
    detailParams_modelShow_signal = pyqtSignal(object)

    def __init__(self, parent=None):
        super().__init__(parent)

    def get_model(self):
        return MeshPartitionData

    def updateUi(self, data):
        data = util_key_map.convertKey(data, 0)
        for k, v in data.items():
            if isinstance(self.gridWidgets[k], QComboBox):
                self.gridWidgets[k].setCurrentText(v)
            else:
                self.gridWidgets[k].setValue(v)


class DlgMeshPartition(DlgModelParams):
    meshPartition_save_signal = pyqtSignal(object)

    def __init__(self, parent=None):
        super(DlgMeshPartition, self).__init__(parent)
        self.setWindowTitle("网格划分")
        self.component = MeshPartitionComponent()
        self.vbox.insertWidget(0, self.component)
        # data = Utils.read_json("data/ipimas/uis/MeshPartition.json")
        # self.updateUi(data)

    def init(self, data):

        self.updateUi(data)

    @pyqtSlot()
    def on_pBtnOK_clicked(self):
        # res = super().on_pBtnOK_clicked()
        valueRes = self.component.getValues()
        # descriptionRes = self.component.getValuesUseDescription()
        file = "data/ipimas/uis/MeshPartition.json"
        data = util_key_map.convertKey(valueRes, 1)
        Utils.write_json(file, data)
        self.close()
        self.meshPartition_save_signal.emit(data)

    def closeEvent(self, event):
        DlgMeshPartition._shown = False  # 使用类名访问类属性
        DlgMeshPartition._instance = None  # 清除实例引用
        event.accept()
